import java.util.Random;

public class Write extends Thread {
    private int num;

    public Write(int num) {
        this.num = num;
        this.setName("写者" + num);
    }

    @Override
    public void run() {
        try {
            Random random = new Random();
            Thread.sleep(random.nextInt(500)); // 模拟准备阶段

            ReadAndWrite.insert3(getName() + " 打算写文件");
            ReadAndWrite.Wr.add(num + "打算写文件");

            // 写者优先控制
            ReadAndWrite.w.acquire();
            ReadAndWrite.rw.acquire();

            // 正在写文件
            ReadAndWrite.insert2(getName() + " 正在写文件");
            ReadAndWrite.ing.add(getName() + " 正在写文件");
            Thread.sleep(random.nextInt(10000) + 3000); // 模拟写操作

            ReadAndWrite.insert2(getName() + " 结束写文件");
            ReadAndWrite.insert3(getName() + " 完成写文件");
            ReadAndWrite.ing.remove(getName() + " 正在写文件");
            ReadAndWrite.Wr.remove(num + "打算写文件");

            Thread.sleep(3000); // 模拟处理完后刷新界面
            ReadAndWrite.fresh.acquire();
            ReadAndWrite.refresh();
            ReadAndWrite.fresh.release();

            ReadAndWrite.rw.release();
            ReadAndWrite.w.release();

        } catch (InterruptedException e) {
            System.out.println(getName() + " 出现错误！");
            e.printStackTrace();
        }
    }
}
